package com.cloud.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.cloud.common.constant.ProcessConstants;
import com.cloud.service.FeignSystemService;
import com.cloud.utils.SpringUtils;
import lombok.AllArgsConstructor;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * 多实例流程处理类
 * 会签,并行,串行
 */
@AllArgsConstructor
@Component("multiInstanceHandler")
public class MultiInstanceHandler {

    public Set<String> getUserIds(DelegateExecution execution) {
        Set<String> candidateUserIds = new LinkedHashSet<>();
        FlowElement flowElement = execution.getCurrentFlowElement();
        if (ObjectUtil.isNotEmpty(flowElement) && flowElement instanceof UserTask) {
            UserTask userTask = (UserTask) flowElement;
            String dataType = userTask.getAttributeValue(ProcessConstants.NAMASPASE,
                    ProcessConstants.PROCESS_CUSTOM_DATA_TYPE);
            if ("USERS".equals(dataType) && CollUtil.isNotEmpty(userTask.getCandidateUsers())) {
                // 添加候选用户ID
                candidateUserIds.addAll(userTask.getCandidateUsers());
            } else if (CollUtil.isNotEmpty(userTask.getCandidateGroups())) {
                List<Long> userIds = new ArrayList<>();
                // 获取组的ID,角色ID集合或部门ID集合
                String groups = CollUtil.join(userTask.getCandidateGroups(), ",");
                if ("ROLES".equals(dataType)) {
                    // 通过角色id,获取所有用户id集合
                    userIds = SpringUtils.getBean(FeignSystemService.class).getRoleUserIdsById(groups).getData();
                } else if ("DEPTS".equals(dataType)) {
                    // 通过部门ID,获取所有用户ID集合
                    userIds = SpringUtils.getBean(FeignSystemService.class).getDeptUserIdsById(groups).getData();
                }
                // 添加候选用户id
                userIds.forEach(id -> candidateUserIds.add(String.valueOf(id)));
            }
        }
        return candidateUserIds;
    }

}
